package com.tianji.learning.mq;

import com.tianji.api.dto.trade.OrderBasicDTO;
import com.tianji.common.constants.MqConstants;
import com.tianji.common.utils.CollUtils;
import com.tianji.common.utils.ObjectUtils;
import com.tianji.learning.service.ILearningLessonService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

/**
 * @Description LessonChangeListener
 * @Author apeng
 * @Date 2024-12-07
 */
@Slf4j
@Component
@RequiredArgsConstructor      //通过构造函数注入
public class LessonChangeListener {

    private final ILearningLessonService learningLessonService;

    //定义监听器，监听订单服务发送过来的信息
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "learning.lesson.pay.queue",durable = "true"),
            exchange = @Exchange(name = "MqConstants.Exchange.ORDER_EXCHANGE",type = ExchangeTypes.TOPIC),
            key = MqConstants.Key.ORDER_PAY_KEY
    ))
    public void listenLessonPay(OrderBasicDTO order){

        if (order == null || order.getUserId() == null || CollUtils.isEmpty(order.getCourseIds())){

            log.error("接收到MQ信息有误，订单数据为空");
            return;
        }
        //添加课程
        log.info("监听到用户{}的订单，需要添加课程{}到课表中",order.getUserId(),order.getCourseIds());
        learningLessonService.addUserLessons(order.getUserId(),order.getCourseIds());
    }

    //定义监听器,报名退款通知
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "learning.lesson.refund.queue",durable = "true"),
            exchange = @Exchange(name = "MqConstants.Exchange.ORDER_EXCHANGE",type = ExchangeTypes.TOPIC),
            key = MqConstants.Key.ORDER_REFUND_KEY
    ))
    public void listenLessonRefund(OrderBasicDTO order){

        if (order == null || order.getUserId() == null
                || CollUtils.isEmpty(order.getCourseIds()) || ObjectUtils.isEmpty(order.getOrderId())){

            log.error("接收到MQ信息有误，订单数据为空");
            return;
        }
        //添加课程
        log.info("监听到用户{}的订单，需要添加课程{}到课表中",order.getUserId(),order.getCourseIds());
        learningLessonService.deleteLessons(order.getUserId(),order.getCourseIds());
    }
}
